package com.boot2.core.web;

import com.boot2.core.constant.I18nMessageContantKey;
import com.boot2.core.utils.DateUtil;
import com.boot2.core.utils.MessageSourceUtil;
import com.boot2.core.utils.MySimpleDateFormat;
import com.boot2.core.utils.StringUtils;
import com.google.common.collect.Lists;
import lombok.extern.apachecommons.CommonsLog;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author zhangweilin
 * @date 2018/7/4 17:15
 * @description: 日期转换处理 此为接收客户端参数，然后转换成Date到业务代码中
 */
@CommonsLog
public class DateEditor extends PropertyEditorSupport {

    private static final ThreadLocal<List<SimpleDateFormat>> sdfThreadLocal = ThreadLocal.withInitial(() ->
            Lists.newArrayList(
                    new MySimpleDateFormat(MessageSourceUtil.getI18nMessage(I18nMessageContantKey.date_format_in, DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss)),
                    new MySimpleDateFormat(MessageSourceUtil.getI18nMessage(I18nMessageContantKey.datetime_format_in, DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss)),
                    new MySimpleDateFormat(MessageSourceUtil.getI18nMessage(I18nMessageContantKey.time_format_in, DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss)))
    );

    private static DateEditor dateEditor = null;

    public static synchronized DateEditor getInstance() {
        if (null == dateEditor) {
            dateEditor = new DateEditor();
        }
        return dateEditor;
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (StringUtils.isEmpty(text)) {
            return;
        }
        List<SimpleDateFormat> simpleDateFormatList = sdfThreadLocal.get();
        for (SimpleDateFormat sdf : simpleDateFormatList) {
            Date date = null;
            try {
                date = sdf.parse(text);
            } catch (ParseException e) {
                log.warn("使用格式【" + sdf.toPattern() + "】转换字符串【" + text + "】时出错!!!请注意使用正确的日期时间格式");
            }
            if (null != date) {
                setValue(date);
                return;
            }
        }

        SimpleDateFormat format = new SimpleDateFormat(MessageSourceUtil.getI18nMessage(I18nMessageContantKey.date_format_in, null, DateUtil.PATTERN_yyyy_MM_dd));
        Date date = null;
        try {
            date = format.parse(text);
        } catch (ParseException e) {
            //以系统默认的还转换失败，则最后尝试一次用毫秒转换
            try {
                date = new Date(Long.parseLong(text));
            } catch (NumberFormatException numberFormatException) {
                log.warn("日期时间参数尝试以毫秒转换仍然失败,",numberFormatException);
            }
        }
        setValue(date);
    }
}
